#encoding=utf8
from resource_management import *
from resource_management.core.resources.system import Execute
from resource_management.libraries.script.script import Script
from griffin_env import griffin_env
import time
import os

class Griffin(Script):
    def install(self, env):
        import params
        env.set_params(params)
        # 删除现有的软连接
        Execute('rm -rf /usr/hdp/current/{0}'.format(params.app_name))
        # 删除已有的grffin 目录
        Execute("rm -rf {0}".format(params.griffin_base_dir))
        # griffin
        Execute('rm -rf {0}{1}*'.format(params.hdp_base_dir, params.app_name))
        # 从yum源拉取源码包
        Execute('wget {0} -O {1}.tar.gz'.format(params.griffin_download_url, params.app_name))
        # 创建文件夹
        Execute('mkdir {0}'.format(params.griffin_base_dir))
        # 解压缩源码包
        Execute('tar -zxvf {0}.tar.gz -C {1} && rm -rf griffin.tar.gz'.format(params.app_name, params.griffin_base_dir))
        # 创建目录软链至current
        Execute('ln -s {0} /usr/hdp/current/griffin'.format(params.griffin_base_dir))

        Logger.info("Get source package complete")

        self.configure(env)

    def start(self, env):
        import params
        env.set_params(params)
        self.configure(env)
        start_cmd = format("sh " + params.griffin_sh_path + ' start')
        Execute(start_cmd, user=params.griffin_user)
        print('start')
        # Execute('sh {0}griffin.sh start')

    def stop(self, env):
        print('begin to stop')
        import params
        env.set_params(params)
        # Stop GRIFFIN
        stop_cmd = format("sh " + params.griffin_sh_path + ' stop')
        Execute(stop_cmd, user=params.griffin_user)
        Execute('ps -ef | grep griffin | grep -v grep |awk \'{print $2}\' | xargs kill -9',
                user=params.griffin_user,
                ignore_failures=True
                )
        # 删除pid文件
        File([params.griffin_pid_file],
             action="delete")

        Logger.info("Stop complete!")
        time.sleep(5)

    def configure(self, env):
        import params
        params.pika_slave = True
        env.set_params(params)
        griffin_env() # 这个只是引用了一些params上的路径变量

    def status(self, env):
        import status_params
        env.set_params(status_params)
        check_process_status(status_params.elastic_pid_file)


if __name__ == "__main__":
  Griffin().execute()

